import { User } from "screens/project-list/search-panel"

const localStorageKey = '__auth_provider_token__'

const apiUrl = process.env.REACT_APP_API_URL

export function getToken() {
  return localStorage.getItem(localStorageKey)
}

export function handleUserResponse({user}: { user: User }) {
  localStorage.setItem(localStorageKey, user.token || '')
  return user
}

export function login(data: {username: string, password: string}) {
  return fetch(`${apiUrl}/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }).then(async response => {
    if (response.ok) {
      return handleUserResponse(await response.json())
    } else {
      return Promise.reject(await response.json())
    }
  })
}

export function register(data: {username: string, password: string}) {
  return fetch(`${apiUrl}/register`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }).then(async response => {
    if (response.ok) {
      return handleUserResponse(await response.json())
    } else {
      return Promise.reject(await response.json())
    }
  })
}

export async function logout() {
  return localStorage.removeItem(localStorageKey)
}
